package com.gitee.qdbp.vmall.web.controller.sales.mgr.order;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.model.paging.PageList;
import com.gitee.qdbp.able.result.ResponseMessage;
import com.gitee.qdbp.base.model.condition.OrderPaging;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.base.utils.EnumTools;
import com.gitee.qdbp.base.utils.SessionTools;
import com.gitee.qdbp.general.common.api.settings.model.AreaDivisionBean;
import com.gitee.qdbp.general.common.api.settings.model.AreaDivisionWhere;
import com.gitee.qdbp.general.common.api.settings.service.IAreaDivisionQueryer;
import com.gitee.qdbp.general.common.enums.AreaType;
import com.gitee.qdbp.general.trade.api.order.main.model.OrderFormBean;
import com.gitee.qdbp.general.trade.api.order.main.model.OrderFormWhere;
import com.gitee.qdbp.general.trade.api.order.main.model.OrderItemBean;
import com.gitee.qdbp.general.trade.api.order.main.model.OrderItemWhere;
import com.gitee.qdbp.general.trade.api.order.main.service.IOrderMainExecutor;
import com.gitee.qdbp.general.trade.api.order.main.service.IOrderMainQueryer;
import com.gitee.qdbp.general.trade.enums.OrderState;
import com.gitee.qdbp.vmall.sales.api.goods.manage.model.InventoryRealtimeBean;
import com.gitee.qdbp.vmall.sales.api.goods.manage.service.IInventoryRealtimeQueryer;
import com.gitee.qdbp.vmall.sales.api.order.main.model.CarrierBean;
import com.gitee.qdbp.vmall.sales.api.order.main.service.IGoodsOrderExecutor;
import com.gitee.qdbp.vmall.web.controller.sales.mgr.order.model.GoodsOrderItemDetails;

/**
 * 订单基本信息控制器
 *
 * @author zhaohuihua
 * @version 170809
 */
@Controller
@RequestMapping("actions/order/form")
public class OrderFormController {

    @Autowired
    private IOrderMainQueryer orderMainQueryer;
    @Autowired
    private IOrderMainExecutor orderMainExecutor;
    @Autowired
    private IGoodsOrderExecutor goodsOrderExecutor;
    @Autowired
    private IAreaDivisionQueryer areaDivisionQueryer;
    @Autowired
    private IInventoryRealtimeQueryer inventoryRealtimeQueryer;

    /** 查询订单列表 **/
    @ResponseBody
    @RequestMapping("list")
    @RequiresPermissions("order:form:query")
    public ResponseMessage list(OrderFormWhere model, OrderPaging paging, Boolean extra) {
        try {
            PageList<OrderFormBean> list = orderMainQueryer.list(model, paging);
            ResponseMessage result = new ResponseMessage(list.toList());
            if (Boolean.TRUE.equals(extra)) {
                result.addExtra(EnumTools.getEnumsResource(OrderState.class));
                // result.addExtra("User", memberCoreQueryer.listByCreatorIds(list.toPageList(), operator));
                { // 查询城市列表
                    AreaDivisionWhere w = new AreaDivisionWhere();
                    w.addType(AreaType.PROVINCE, AreaType.CITY);
                    OrderPaging p = OrderPaging.of("type asc, sortIndex asc, areaCode asc");
                    PageList<AreaDivisionBean> areas = areaDivisionQueryer.list(w, p);
                    result.addExtra("Area", areas.toList());
                }
                // { // 查询当前用户拥有权限的门店列表
                //     List<SimpleSystemBean> owner = ManagerServiceRealm.queryOwnerShops();
                //     result.addExtra("Shop", owner);
                // }
            }
            return result;
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 查询订单明细 **/
    @ResponseBody
    @RequestMapping("items")
    @RequiresPermissions("order:form:query")
    public ResponseMessage items(String id, OrderPaging paging, Boolean extra) {
        try {
            PageList<GoodsOrderItemDetails> paged = listItems(id, paging);
            ResponseMessage result = new ResponseMessage(paged);
            if (Boolean.TRUE.equals(extra)) {
                result.addExtra(EnumTools.getEnumsResource(OrderState.class));
            }
            return result;
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 取消订单(待支付变成已取消) **/
    @ResponseBody
    @RequestMapping("cancel")
    @RequiresPermissions("order:form:cancel")
    public ResponseMessage cancel(String id, String description) {
        try {
            IAccount operator = SessionTools.getLoginUser();
            orderMainExecutor.cancel(id, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 核销订单(顾客自提) **/
    @ResponseBody
    @RequestMapping("deliver-by-taken")
    @RequiresPermissions("order:form:deliver")
    public ResponseMessage deliver(String id, CarrierBean carrier, String description) {
        try {
            IAccount operator = SessionTools.getLoginUser();
            goodsOrderExecutor.deliverByCarrier(id, carrier, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 删除无效订单 **/
    @ResponseBody
    @RequestMapping("delete-ineffective")
    @RequiresPermissions("order:form:delete:ineffective")
    public ResponseMessage deleteIneffectiveRecord(String id, String description) {
        try {
            IAccount operator = SessionTools.getLoginUser();
            orderMainExecutor.deleteIneffectiveRecord(id, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 删除有效订单 **/
    @ResponseBody
    @RequestMapping("delete-effective")
    @RequiresPermissions("order:form:delete:effective")
    public ResponseMessage deleteEffectiveRecord(String id, String description) {
        try {
            IAccount operator = SessionTools.getLoginUser();
            orderMainExecutor.deleteEffectiveRecord(id, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    private PageList<GoodsOrderItemDetails> listItems(String orderId, OrderPaging paging) throws ServiceException {
        PageList<OrderItemBean> items;
        { // 查询订单明细
            OrderItemWhere w = new OrderItemWhere();
            w.setOrderId(orderId);
            items = orderMainQueryer.listItems(w, paging);
        }
        if (items.isEmpty()) {
            return PageList.of(new ArrayList<>());
        }

        // 订单列表用到的商品字段较少, 暂不需要查询商品详情
        // PageList<GoodsVersionBean> goodses;
        // { // 查询商品详情
        //     Set<String> goodsVids = new HashSet<>();
        //     for (OrderItemBean item : items) {
        //         goodsVids.add(item.getGoodsVid());
        //     }
        //     GoodsVersionWhere w = new GoodsVersionWhere();
        //     w.setVids(new ArrayList<>(goodsVids));
        //     goodses = goodsVersionQueryer.list(w, OrderPaging.NONE);
        // }
        List<InventoryRealtimeBean> inventories;
        { // 查询实时库存
            Set<String> skuIds = new HashSet<>();
            for (OrderItemBean item : items) {
                skuIds.add(item.getSkuId());
            }
            inventories = inventoryRealtimeQueryer.listBySkuId(new ArrayList<>(skuIds));
        }

        // 组合
        List<GoodsOrderItemDetails> temp = OrderItemBean.to(items.toList(), GoodsOrderItemDetails.class);
        PageList<GoodsOrderItemDetails> result = PageList.of(temp);
        for (GoodsOrderItemDetails item : result) {
            // for (GoodsVersionBean goods : goodses) {
            //     if (item.getGoodsVid().equals(goods.getVid())) {
            //         // 复制, 否则生成的JSON会出现对象引用
            //         GoodsVersionBean copy = goods.to(GoodsVersionBean.class);
            //         item.setGoods(copy);
            //         break;
            //     }
            // }
            for (InventoryRealtimeBean inventoriy : inventories) {
                if (item.getSkuId().equals(inventoriy.getSkuId())) {
                    item.setStockQuantity(inventoriy.getStockQuantity());
                    item.setSoldQuantity(inventoriy.getSoldQuantity());
                    break;
                }
            }
        }

        return result;
    }
}
